<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\JwtService;
use Illuminate\Http\Request;
use Hash;
use App\Repositories\UserRepo;
use App\Exceptions\ValidationException;

class LoginController extends ApiBaseController
{
    public function index(Request $request)
    {
        return $this->errRes(5000, '请登录');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        $request->validate([
            'account' => 'required',
            'password' => 'required'
        ]);
        $account = $request->input('account', '');
        $password = $request->input('password', '');
        $mobile = $request->input('mobile', '');


        $userRepo = new UserRepo();
        $user = $userRepo->getUserByPassword($account, $password, $mobile);

        if (!$user || !Hash::check($password, $user->password)) {
            throw new ValidationException("账号密码错误" . Hash::make($password, ['rounds' => 12]));
        }
        $jwtService = new JwtService();
        return $this->sucRes(200, [
            'user_info' => [
                'user_name' => $user->user_name,
                'avatar' => $user->avatar
            ],
            'access_token' => $jwtService->createToken($user->id, 'user'),
            'refresh_token' => $jwtService->createToken($user->id, 'user', 7 * 24 * 60 * 60)
        ]);
    }
}
